﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.ComponentModel;
using System.Reflection;
using WorldmeServer.Models.Base;

namespace WorldmeServer.Middlewares
{
    public class BaseResultFilter : IAsyncResultFilter
    {
        /// <summary>
        /// 正常结果过滤器
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            ApiResult apiResult = new ApiResult();
            if (!context.ModelState.IsValid)
            {
                apiResult.Flag = -1;
                apiResult.Message = $"参数序列化错误,错误参数列表:{String.Join(",",context.ModelState.Keys)}";
                context.Result = new JsonResult(apiResult);
            }
            else if(context.Result is ObjectResult res && res.StatusCode != 200)
            {
                apiResult.Flag = -1;
                apiResult.Message = res!.Value.ToString();
                context.Result = new JsonResult(apiResult);
            }
            else if (context.Result is ObjectResult)
            {
                res = (ObjectResult)context.Result;
                apiResult.Flag = 0;
                apiResult.Data = res!.Value;
                context.Result = new JsonResult(apiResult);
                if (context.HttpContext.Response.StatusCode == 401)
                {
                    apiResult.Flag = -1;
                    apiResult.Message = "未授权的请求";
                }
            }
            if (context.Result is not EmptyResult)
            {
                await next();
            }
            else
            {
                context.Cancel = true;
            }
        }
    }
}
